<script lang="ts">
    import { useClassList } from "../utils/useClassList";
    import type { ListItemProps } from "./List";
    import { useListContext } from "./List.svelte";

    const props: ListItemProps = $props();
    const ctx = useListContext();

    let activeKey = ctx?.activeKey?.();

    const classList = $derived(
        useClassList(props, "cm-list-item", {
            "cm-list-item-active": activeKey === props.id,
        })
    );

    const onClick = () => {
        if (ctx?.selectable) {
            activeKey = props.id;
            ctx?.onSelect && ctx.onSelect(props.data);
        }
    };
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class={classList} style={props.style} onclick={onClick}>
    <div class="cm-list-item-main">
        <div class="cm-list-item-meta">
            {#if props.avatar}
                <div class="cm-list-item-avatar">{@render props.avatar?.()}</div>
            {/if}
            {#if props.title || props.desc}
                <div class="cm-list-item-body">
                    <div class="cm-list-item-title">
                        {#if typeof props.title === "function"}
                            {@render props.title()}
                        {:else}
                            {props.title}
                        {/if}
                    </div>
                    <div class="cm-list-item-desc">
                        {#if typeof props.desc === "function"}
                            {@render props.desc()}
                        {:else}
                            {props.desc}
                        {/if}
                    </div>
                </div>
            {/if}
        </div>
        {#if props.children}
            <div class="cm-list-item-content">
                {@render props.children?.()}
            </div>
        {/if}
    </div>
    {#if props.actions}
        <ul class="cm-list-item-addon">
            {@render props.actions()}
        </ul>
    {/if}
</div>
